package com.iwunu.gateway.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.iwunu.gateway.entity.FLock;
import com.iwunu.gateway.entity.FLockMember;
import com.iwunu.gateway.entity.FaceLock;
import com.iwunu.gateway.entity.ImageMongo;
import com.iwunu.gateway.repository.FaceLocMemberRepository;
import com.iwunu.gateway.repository.FaceLockRepository;
import com.iwunu.gateway.service.FaceLockMemberService;
import com.iwunu.gateway.service.ImageMongodbService;

import cn.hutool.core.bean.BeanUtil;

@Service
public class FaceLockMemberServiceImpl implements FaceLockMemberService{
	  @Autowired
	  private FaceLocMemberRepository lockmemberRepository;
	  @Autowired
	  private FaceLockRepository faceLockRepository;
	  @Autowired 
	  private ImageMongodbService imageMongodbService;
	  

	@Override
	public  List<Map<String, Object>> selectFaceLockMembers(Integer lockId) {
		return lockmemberRepository.selectFaceLockMembers(lockId);
	}
	@Override
	public List<Map<String, Object>> authList(Integer lockId) {
		return lockmemberRepository.authList(lockId);
	}
	
	@Override
	public int updateByLockIdAndUserId(Integer userId, Integer lockId) {
		return lockmemberRepository.updateByLockIdAndUserId(userId, lockId);
	}

	@Override
	public int delByLockMemberId(Long lockMemberId) {
		return lockmemberRepository.delByLockMemberId(lockMemberId);
	}
	@Override
	public int delByLockId(Integer lockId) {
		return lockmemberRepository.delByLockId(lockId);
	}
	@Override
	public FLockMember sava(JSONObject fl) {
		FLockMember fm = new FLockMember();
		fm.setCreateTime(new Date());
		fm.setLockClientId(fl.getString("lockClientId"));
		fm.setLockId(fl.getIntValue("lockId"));
		fm.setUserId(fl.getIntValue("userId"));
		fm.setRole(null);
		fm.setIsDel(false);
		fm.setRemark(fl.getString("remark"));
		return lockmemberRepository.save(fm);
	}
	@Override
	public int auth(Integer lockMemberId,Integer role) {
		return lockmemberRepository.auth(Long.valueOf(lockMemberId),role);
	}
	
	@Override
	public List<Map<String, Object>> selectByUserFaceLocks(Integer userId) {
		return lockmemberRepository.selectByUserFaceLocks(userId);
	}
	@Override
	public Map<String, Object> selectByAdminFaceLocks(String bussinessNo,Integer pageSize,Integer currentPage,String name) {
		Map<String, Object> result =  new HashMap<String, Object>();
		List<FLock> lockList = new ArrayList<FLock>();
		 Specification<FaceLock> specification = new Specification<FaceLock>() {
			private static final long serialVersionUID = 1L;

				public Predicate toPredicate(Root<FaceLock> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
	                List<Predicate> predicates = new ArrayList<>();
	                if (StringUtils.isNotBlank(name)) {
	                    // 模糊查询
	                	Predicate likeNickName = cb.like(root.get("name").as(String.class),"%" + name + "%");
	                    predicates.add(likeNickName);
	                }
	                    // 精确查询
	                    Path<String> bussinessId = root.get("bussinessId");
	                    predicates.add(cb.equal(bussinessId.as(String.class), bussinessNo));
	                    predicates.add(bussinessId.isNotNull());
	                    // 精确查询
	                    Path<Boolean> isDel = root.get("isDel");
	                    predicates.add(cb.equal(isDel.as(Boolean.class), false));
	                Predicate[] p = new Predicate[predicates.size()];
	                return cb.and(predicates.toArray(p));
	            }
	        };
	        // page默认从0开始，实际应用从1开始，因此此处page-1
	        Pageable page = PageRequest.of(currentPage,pageSize, Sort.by(Sort.Direction.DESC, "id"));
	        Page<FaceLock> lockpage = faceLockRepository.findAll(specification, page);
		 for(FaceLock flock :lockpage.getContent()) {
			 List<ImageMongo> images = imageMongodbService.getSendImageData(flock.getClientId());
			 FLock lock = BeanUtil.copyProperties(flock, FLock.class);
			 lock.setCount(images==null?0:images.size());
			 lock.setLockId(flock.getId());
			 lockList.add(lock);
		 }
		 result.put("content", lockList);
		 result.put("pageSize", pageSize);
		 result.put("currentPage", currentPage);
		 result.put("totalPage", lockpage.getTotalPages());
		 result.put("totalCount", lockpage.getTotalElements());
		 return result ;
	}
	@Override
	public List<Map<String, Object>> selectMyFaceLocks(Integer userId) {
		return lockmemberRepository.selectMyFaceLocks(userId);
	}	
	
	
	public FLockMember findFaceLockMember( Integer userId,Integer lockId) {
		return lockmemberRepository.findFaceLockMember(userId,lockId);
	}
//	public FLockMember findFaceLockAdmin( String bussinessId,Integer lockId) {
//		return lockmemberRepository.findFaceLockAdmin(bussinessId,lockId);
//	}
	public FLockMember findById( Long id) {
		return lockmemberRepository.findMemberById(id);
	}	
	
	public Map<String, Object>  findLockInfo(Integer userId, Integer lockId) {
		return lockmemberRepository.findLockInfo(userId, lockId);
	}
	public int changeMember(List<Integer> lockIds, Integer userId,String userNo) {
		if(StringUtils.isNoneBlank(userNo)) {
			faceLockRepository.changeMember(lockIds, userId,userNo);
		}else {
			faceLockRepository.changeMember(lockIds, userId);
		}
		return lockmemberRepository.changeMember(lockIds, userId);
	}
	public int changePushMember(List<Integer> lockIds, Integer userId,String userNo) {
		 faceLockRepository.changePushMember(lockIds, userId,userNo);
		return lockmemberRepository.changeMember(lockIds, userId);
	}
	@Override
	public int delByLockIds(List<Integer> lockIds) {
		return lockmemberRepository.delByLockIds(lockIds);
	}
	public static void main(String[] args) {
		System.out.println(StringUtils.isNotBlank(null));
	}
}

